package net.stogi.common.gwt.dispatch.server.core.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.stogi.common.gwt.dispatch.server.core.ActionHandler;
import net.stogi.common.gwt.dispatch.server.core.InstanceActionHandlerRegistry;
import net.stogi.common.gwt.dispatch.shared.core.Action;
import net.stogi.common.gwt.dispatch.shared.core.Result;

public class InstanceActionHandlerRegistryImpl<A extends Action<R>, R extends Result> implements
		InstanceActionHandlerRegistry<A, R> {

	private final Map<Class<A>, ActionHandler<A, R>> handlers;

	public InstanceActionHandlerRegistryImpl() {
		handlers = new HashMap<Class<A>, ActionHandler<A, R>>(100);
	}

	public InstanceActionHandlerRegistryImpl(List<ActionHandler<A, R>> handlers) {
		this();
		for (ActionHandler<A, R> handler : handlers) {
			addHandler(handler);
		}
	}

	public void addHandler(ActionHandler<A, R> handler) {
		handlers.put(handler.getActionType(), handler);
	}

	public void clearHandlers() {
		handlers.clear();
	}

	public ActionHandler<A, R> findHandler(A action) {
		return (ActionHandler<A, R>) handlers.get(action.getClass());
	}

	public boolean removeHandler(ActionHandler<A, R> handler) {
		return handlers.remove(handler.getActionType()) != null;
	}
}
